package main

import (
	"crypto/md5"
	"encoding/base64"
	"fmt"
	"go.manyji.com/lib/util/convert"
	"io"
	"net/http"
	stdurl "net/url"
	"sort"
	"strings"
	"sync"
	"time"
)

var (
	host     = "http://127.0.0.1:10087/"
	hostAda  = "http://192.168.1.30:10085"
	AesKey   = "fZ9&N6ufs4gACs@a"
	logInMap = sync.Map{}
)

func callApi(api string, body, header map[string]string) (string, error) {

	var (
		deviceId    = header["device_id"]
		reqSource   = header["req_source"]
		token       = AesKey
		url         = host + api
		tNow        = time.Now().Unix()
		contentType = "application/x-www-form-urlencoded" // 设置请求的 Content-Type
		s           = api
		keys        []string
		publicArg   = stdurl.Values{
			"deviceId":  {deviceId},
			"reqSource": {reqSource},
		}.Encode()
		bodyArg = stdurl.Values{}
	)

	if v, ok := logInMap.Load(deviceId); ok {
		token = v.(string)
	}

	// param 加密
	paramByte, err := AesEncrypt([]byte(AesKey), []byte(AesKey), []byte(publicArg))
	if err != nil {
		return "", err
	}
	// 转base64
	paramStr := base64.StdEncoding.EncodeToString(paramByte)

	if body == nil {
		body = map[string]string{}
	}
	body["t"] = fmt.Sprintf("%v", tNow)
	body["param"] = fmt.Sprintf("%v", paramStr)
	for k, v := range body {
		bodyArg.Add(k, v)

		if strings.HasPrefix(k, "_") {
			continue
		}
		keys = append(keys, k)
	}

	sort.Strings(keys)
	for _, key := range keys {
		value := body[key]
		s += key + "=" + value
	}

	s += token
	sig := GetMD5Upper(s)
	bodyArg.Add("sig", sig)
	payload := strings.NewReader(bodyArg.Encode())
	// 设置请求的请求体

	// 创建一个请求的实例
	req, err := http.NewRequest("POST", url, payload)
	if err != nil {
		fmt.Println("创建请求失败:", err)
		return "", err
	}

	// 设置请求的 Header
	req.Header.Add("Content-Type", contentType)

	for k, v := range header {
		req.Header.Add(k, v)
	}

	// 发起请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("POST请求出错:", err)
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应内容
	repBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("读取响应内容失败:", err)
		return "", err
	}
	return string(repBody), nil
}

// 管理端接口调用
func callAdaApi(api string, body, header map[string]string) (string, error) {
	url := hostAda + "/" + api
	contentType := "application/x-www-form-urlencoded" // 设置请求的 Content-Type

	bodyStr := ""
	for k, v := range body {
		if bodyStr == "" {
			bodyStr = bodyStr + k + "=" + v
		} else {
			bodyStr = bodyStr + "&" + k + "=" + v
		}
	}
	payload := strings.NewReader(bodyStr)
	// 设置请求的请求体
	// bodyByte, _ := json.Marshal(body)

	// 创建一个请求的实例
	req, err := http.NewRequest("POST", url, payload)
	if err != nil {
		fmt.Println("创建请求失败:", err)
		return "", err
	}

	// 设置请求的 Header
	req.Header.Add("Content-Type", contentType)

	for k, v := range header {
		req.Header.Add(k, v)
	}

	// 发起请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("POST请求出错:", err)
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应内容
	repBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("读取响应内容失败:", err)
		return "", err
	}
	return string(repBody), nil
}

// 充值
func recharge(activityId int64, deviceId string) (string, error) {
	body := map[string]string{
		"activity_id": fmt.Sprint(activityId),
	}
	header := map[string]string{
		"device_id": deviceId,
	}

	return callApi("Recharge", body, header)
}

// 充值回调
func rechargeFeedBack(status, timeout int, orderNo, deviceId string) (string, error) {
	body := map[string]string{
		"status":  fmt.Sprint(status),
		"token":   orderNo,
		"timeout": fmt.Sprint(timeout),
	}
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("PayPalCallBack", body, header)
}

// 用户信息
func getUserInfo(deviceId string) (string, error) {
	body := map[string]string{}
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("GetUserInfo", body, header)
}

// 解锁影片
func unlockFilmEpisode(filmId, get_price int, episodes, deviceId string, auto string) (string, error) {
	body := map[string]string{
		"episodes": episodes,
		"film_id":  fmt.Sprint(filmId),
		"auto":     auto,
	}
	if get_price != 0 {
		body["get_price"] = fmt.Sprint(get_price)
	}
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("UnlockFilmEpisode", body, header)
}

// 影片列表
func filmForYou(deviceId string) (string, error) {
	body := map[string]string{}
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("FilmForYou", body, header)
}

func getFilmCategoryList() (string, error) {
	body := map[string]string{}
	header := map[string]string{
		"device_id": "xxx",
	}
	return callApi("GetFilmCategoryList", body, header)
}

func getFilmList(filmCategoryId, pageIndex int, pageSize int) (string, error) {
	body := map[string]string{
		"film_category_id": convert.ToString(filmCategoryId),
		"page_index":       convert.ToString(pageIndex),
		"page_size":        convert.ToString(pageSize),
	}
	header := map[string]string{
		"device_id": "xxx",
	}
	return callApi("GetFilmList", body, header)
}

func getFilmDetail(id int64, deviceId string) (string, error) {
	body := map[string]string{
		"id": convert.ToString(id),
	}
	header := map[string]string{
		"device_id": "xxx",
	}
	return callApi("GetFilmDetail", body, header)
}

// 活动列表
func getAcitityList(deviceId string) (string, error) {
	body := map[string]string{}
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("GetActivities", body, header)
}

// 添加影片
func addFilm(filmData map[string]string) (string, error) {
	return callAdaApi("/film/collection/add_item", filmData, nil)
}

// 绑定邮箱(直接验证)
func bindEmail(deviceId, email, code string) (string, error) {
	body := map[string]string{
		"device_id": deviceId,
		"email":     email,
		"code":      code,
	}
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("VerifyEmail", body, header)
}

// 首次登录
func firstView(deviceId string) (string, error) {
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("FirstVisit", nil, header)
}

// 邮箱登录
func loginByEmail(deviceId, email string) (string, error) {
	body := map[string]string{
		"email": email,
	}
	header := map[string]string{
		"device_id": deviceId,
	}
	return callApi("Login", body, header)
}

func GetMD5(s string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}
